<!-- Author: Edwin -->
<template>
  <el-dialog :visible.sync="showDialog"
             :close-on-press-escape="false"
             :close-on-click-modal="false"
             append-to-body
             destroy-on-close
             class="block-model-dialog"
             width="1000px">
    <div slot="title">
      <div class="title">
        {{ blockInfo.name }}
        <!-- <el-tag v-if="blockInfo.type === 'trigger'"
                size="mini"
                hit
                type="success">{{ blockInfo.type }}</el-tag>
        <el-tag v-if="blockInfo.type === 'action'"
                size="mini"
                hit
                type="danger">{{ blockInfo.type }}</el-tag>
        <el-tag v-if="blockInfo.type === 'logger'"
                size="mini"
                hit
                type="warning">{{ blockInfo.type }}</el-tag> -->
      </div>
    </div>
    <!-- <div class="description">{{ blockInfo.description }}</div> -->
    <el-card shadow="never">
      <template v-if="hasLayout">
        <ScriptRender v-if="dialogVisible"
                      ref="script-render"
                      :blockInfo='blockInfo'
                      @transmitFilterSqlRes="filterSqlForm"
                      @hiddenSettingModel="hiddenSettingModels"
                      :showJson='layoutScriptJson'
                      :dataForm='dataForm'>
          <template v-slot:layout>
            <ScriptRender v-if="dialogVisible"
                          ref="script-render"
                          :blockInfo='blockInfo'
                          @transmitFilterSqlRes="filterSqlForm"
                          @hiddenSettingModel="hiddenSettingModels"
                          :showJson='noLayoutScriptJson'
                          :dataForm='dataForm'></ScriptRender>
          </template>
        </ScriptRender>
      </template>
      <template v-else>
        <ScriptRender v-if="dialogVisible"
                      ref="script-render"
                      :blockInfo='blockInfo'
                      @hiddenSettingModel="hiddenSettingModels"
                      @transmitFilterSqlRes="filterSqlForm"
                      :showJson='scriptJson'
                      :dataForm='dataForm'></ScriptRender>
      </template>
    </el-card>
    <span slot="footer"
          class="dialog-footer">
      <el-button type="primary"
                 v-if="onlyHasOneLine && nowBlockId > 0 && nowBlockId < 8888"
                 @click="previousSettingModel"
                 plain
                 size="mini">Previous</el-button>
      <!-- <el-button @click="dialogVisible = false"
                 size="mini">Cancel</el-button> -->
      <el-button @click="saveDataForm"
                  v-if="onlyHasOneLine && lastBlockId === nowBlockId"
                 size="mini">{{$t('custom.bots.edit.finish')}}</el-button>
      <el-button type="primary"
                 v-if="onlyHasOneLine && lastBlockId > nowBlockId"
                 @click="nextSettingModel"
                 plain
                 size="mini">Next</el-button>
    </span>
  </el-dialog>
</template>

<script>
import ScriptRender from '@/components/script-render/index'
import { flowy } from '../flowy'
import { generalConvertJsonToSQL } from '@/utils/common'

export default {
  components: { ScriptRender },
  inject: {
    scriptList: {
      default: () => { }
    }
  },
  data () {
    return {
      dialogVisible: false,
      blockInfo: {},
      scriptJson: [],
      dataForm: {},
      tempEvent: null,
      onlyHasOneLine: false,
      nowBlockId: 9999,
      lastBlockId: -1
    }
  },
  computed: {
    blocksList () {
      return this.scriptList()
    },
    hasLayout () {
      return this.scriptJson.some(e => e.type === 'layout')
    },
    layoutScriptJson () {
      return this.scriptJson.filter(e => e.type === 'layout')
    },
    noLayoutScriptJson () {
      return this.scriptJson.filter(e => e.type !== 'layout')
    },
    hasCycletemplatemultiple () {
      return this.scriptJson.some(e => e.type === 'cycle-multiple-template')
    },
    cycleScriptJson () {
      return this.scriptJson.filter(e => e.type === 'cycle-multiple-template')
    },
    noCycleScriptJson () {
      return this.scriptJson.filter(e => e.type !== 'cycle-multiple-template' && e.type !== 'layout' && e.type !== 'template-multiple')
    },
    cycleContentScriptJson () {
      return this.scriptJson.filter(e => e.type === 'template-multiple')
    },
    isCycletemplatemultiple () {
      return false
    },
    nowPageName () {
      return this.$store.state.contentTabsActiveName
    },
    showDialog: {
      get () {
        // return Boolean(this.nowPageName === 'mspbots-bots-bak-bot-view-index' && this.dialogVisible)
        return Boolean(this.nowPageName === 'mspbots-bots-bak-bot-design-index' && this.dialogVisible)
      },
      set (val) {
        this.dialogVisible = val
      }
    }
  },
  watch: {
    dataForm: {
      handler (val) {
        if (!this.$store.state.bot.botfromFlag) {
          this.$store.commit('BOTFORMFLAG', true)
        } else {
          this.$store.commit('BOTCONTENTCHANGE', true)
        }
      },
      deep: true
    }
  },
  methods: {
    hiddenSettingModels () {
      this.saveDataForm()
      this.dialogVisible = false
    },
    open (blockInfo, e) {
      this.dialogVisible = true
      this.blockInfo = blockInfo
      this.tempEvent = e
      this.init()
    },
    init () {
      try {
        this.scriptJson = this.blocksList.find(e => e.id === this.blockInfo.id).paramsJson.fields
      } catch (error) {
        this.scriptJson = []
      }
      this.dataForm = this.getSavedDataForm() ? this.getSavedDataForm() : this.getDefaultDataForm(this.scriptJson)
      this.scriptEdit()
      this.computedFlowData()
    },
    otherValidateRules () {
      try {
        return this.$refs['script-render'].toAddressDataValidate() && this.$refs['script-render'].templateMultipleDataValidate() && this.$refs['script-render'].fliterDataValidate('fromBot')
      } catch (e) {
        return false
      }
    },
    validateRules () {
      return this.$refs['script-render'].validateRules()
    },
    checkDataFilter () {
      try {
        return this.$refs['script-render'].checkDataFilter()
      } catch (e) {
        return true
      }
    },
    dataMapping () {
      let temp = this.compatibilityForTriggerFilter(this.dataForm)
      this.tempEvent.closest('.hover-card').setAttribute('paramsValueSend', JSON.stringify(temp))
    },
    compatibilityForTriggerFilter (data) {
      let filterIndex = this.scriptJson.findIndex(e => e.type === 'filter')
      // Is Trigger script
      if (this.hasLayout && filterIndex > -1) {
        let temp = this._.cloneDeep(data)
        temp[this.scriptJson[filterIndex].sqlText] = generalConvertJsonToSQL(data[this.scriptJson[filterIndex].text])
        return temp
      } else {
        return data
      }
    },
    getSavedDataForm () {
      try {
        let temp = JSON.parse(this.tempEvent.closest('.hover-card').getAttribute('paramsValueSend'))
        if (Object.keys(temp).length > 0) {
          return temp
        } else {
          return false
        }
      } catch (error) {
        return false
      }
    },
    getDefaultDataForm (itemJson) {
      if (!Array.isArray(itemJson)) {
        return {}
      }
      let temp = {}
      for (let i = 0; i < itemJson.length; i++) {
        const element = itemJson[i]
        if (typeof element.defaultValue === 'object') {
          temp[element.text] = JSON.parse(JSON.stringify(element.defaultValue))
        } else {
          temp[element.text] = element.defaultValue
        }
      }
      return temp
    },
    async scriptEdit () {
      let trackid = this.tempEvent.closest('.hover-card').getAttribute('trackid')
      let flowSetting = flowy.output()
      let blocks = flowSetting.blocks
      const getAttributeValue = (attr, key) => {
        try {
          let tempData = null
          switch (key) {
            case 'paramsvaluesend':
              tempData = JSON.parse(attr.find(e => Boolean(e[key]) === true)[key])
              break
            case 'trackid':
              tempData = attr.find(e => Boolean(e[key]) === true)[key]
              break
            default:
              break
          }
          return tempData
        } catch (error) {
          return null
        }
      }
      let getBlocksForId = trackid => blocks.find(e => getAttributeValue(e.attr, 'trackid') === trackid)
      let returnData = []
      let getBlock = (trackid) => {
        let obj = getBlocksForId(trackid)
        if (obj.parent !== -1) {
          let parentObj = blocks.find(e => e.id === getBlocksForId(trackid).parent)
          let thisTrackid = getAttributeValue(parentObj.attr, 'trackid')
          if (trackid !== thisTrackid) {
            returnData.push(parentObj)
          }
          getBlock(thisTrackid)
        } else {
          return false
        }
      }
      getBlock(trackid)
      let queryParamsArr = { sysBotScriptList: [] }
      returnData.forEach(item => {
        queryParamsArr.sysBotScriptList.push({ paramsValue: getAttributeValue(item.attr, 'paramsvaluesend') })
      })
      // const { data: res } = await this.$interface.botStore.getKeyOptions(queryParamsArr)
      // if (res.code === 0) {
      //   this.scriptJson.forEach(item => {
      //     if (item.type === 'filter') {
      //       item[item.keyOptions] = res.data
      //     }
      //   })
      // }
      this.getKeyArrayList(getAttributeValue(getBlocksForId(trackid).attr, 'paramsvaluesend'))
    },
    getKeyArrayList (paramsvaluesend) {
      let type = ''
      let id = ''
      this.scriptJson.forEach(item => {
        if (item.type === 'radio-select' && paramsvaluesend[item.text]) {
          type = paramsvaluesend[item.text][item.radioValue]
          id = paramsvaluesend[item.text][item.selectValue]
        }
      })
      if (!type) {
        return false
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.setFilterKeyList([])
            return false
          }
          let temp = []
          res.data.forEach(item => {
            temp.push({
              label: item.name,
              value: item.name,
              type: item.type
            })
          })
          this.setFilterKeyList(temp)
        })
        .catch(() => { })
    },
    setFilterKeyList (list) {
      this.scriptJson.forEach(item => {
        if (item.type === 'filter') {
          item[item.keyOptions] = list
        }
      })
    },
    filterSqlForm () {
      this.$store.commit('FILTERSQL', this.dataForm.filters)
    },
    checkAndValidate () {
      if (!this.otherValidateRules()) {
        return false
      }
      if (!this.checkDataFilter()) {
        return false
      }
      return this.validateRules()
    },
    saveDataForm () {
      if (this.checkAndValidate()) {
        this.checkAndValidate()
          .then(() => {
            this.dataMapping()
            this.dialogVisible = false
          })
          .catch(err => {
            if (!err) {
              this.$message.error('Please check for Form')
            }
          })
      }
    },
    changeModelAndSaveDataForm (blockId) {
      this.$store.commit('BOTFORMFLAG', false)
      if (this.checkAndValidate()) {
        this.checkAndValidate()
          .then(() => {
            this.dataMapping()
            this.changeSettingModel(blockId)
          })
          .catch(err => {
            if (!err) {
              this.$message.error('Please check for Form')
            }
          })
      }
    },
    computedFlowData () {
      this.onlyHasOneLine = this.getHasOneLine()
      this.nowBlockId = this.getNowBlockId()
      this.lastBlockId = this.getLastBlockId()
    },
    getHasOneLine () {
      let hasOneLine = false
      try {
        const flowBlockList = flowy.output().blockarr
        const isRepeat = arr => {
          let temp = []
          let last = []
          for (let i = 0; i < arr.length; i++) {
            temp.push(arr[i]['parent'])
          }
          for (var i = 0; i < temp.length; i++) {
            if (last.indexOf(temp[i]) === -1) {
              last.push(temp[i])
            }
          }
          return Boolean(arr.length === last.length)
        }
        hasOneLine = isRepeat(flowBlockList)
      } catch (e) { }
      return hasOneLine
    },
    getLastBlockId () {
      let lastBlockId = -1
      try {
        const flowBlockList = flowy.output().blockarr
        let temp = []
        for (let i = 0; i < flowBlockList.length; i++) {
          temp.push(flowBlockList[i]['id'])
        }
        lastBlockId = temp.sort()[temp.sort().length - 1]
      } catch (e) { }
      return lastBlockId
    },
    getNowBlockId () {
      let nowBlockId = 9999
      try {
        nowBlockId = this.tempEvent.closest('.hover-card').querySelector('.blockid').getAttribute('value')
      } catch (error) { }
      return Number(nowBlockId)
    },
    previousSettingModel () {
      let blockId = this.nowBlockId - 1
      if (blockId > -1) {
        this.changeModelAndSaveDataForm(blockId)
      }
    },
    nextSettingModel () {
      let blockId = this.nowBlockId + 1
      if (blockId <= this.lastBlockId) {
        this.changeModelAndSaveDataForm(blockId)
      }
    },
    changeSettingModel (blockId) {
      const flowSetting = flowy.output()
      let elementInfo = JSON.parse(flowSetting.blocks[blockId].attr.find(e => Boolean(e.blockinfo) === true).blockinfo)
      let element = document.querySelector(".blockid[value='" + blockId + "']").parentNode
      this.blockInfo = elementInfo
      this.tempEvent = element
      this.init()
    }
  }
}
</script>

<style scoped lang='scss'>
.block-model-dialog{
  ::v-deep .el-dialog__body{
    box-shadow: 0px -1px 0px 0px #F0F0F0;
  }
  ::v-deep .el-dialog__header{
    padding: 20px;
  }
}
.title {
  font-weight: bold;
  font-size: 1.2em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.description {
  padding-bottom: 20px;
}
.el-card {
  border: 0;
}
::v-deep .el-card__body {
  padding: 0 !important;
}
::v-deep .el-dialog__body {
  padding-top: 0;
}
</style>
